import { reqLogin, reqUserInfo, reqUserDatilInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'
export default {
  state() {
    return {
      token: getToken() || '',
      userInfo: {}
    }
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    setUserInfo(state, obj) {
      state.userInfo = obj
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login({ commit }, data) {
      const res = await reqLogin(data)
      // console.log(res)
      commit('setToken', res.data)
    },
    async getUserInfo({ commit }) {
      const { data: data1 } = await reqUserInfo()
      const { data: data2 } = await reqUserDatilInfo(data1.userId)
      const res = { ...data1, ...data2 }
      // console.log(res)
      commit('setUserInfo', res)
    },
    logout({ commit }) {
      commit('removeToken')
      commit('removeUserInfo')
    }
  },
  namespaced: true
}
